const db = uniCloud.database();
const dbJql = uniCloud.databaseForJQL();
const selfUtils = require('self-utils')
const cmd = db.command;
module.exports = {
  _before: async function() { // 通用预处理器
    this.userInfo = await selfUtils.getUserInfo(this)
    if (!this.userInfo.uid) throw this.userInfo;
  },
  async createOrder(data) {
    data.user_id = this.userInfo.uid;
    data.order_no = getOrderId();
    let res = await db.collection("ly-mall-order").add(data);
    return data.order_no;
  },
  // 获取订单列表 过滤掉未支付的
  async getList(pageNum = 1) {
    let pageSize = 5;
    let res = await dbJql.collection("ly-mall-order").where({
      user_id: this.userInfo.uid,
      status: cmd.neq(0)
    }).orderBy('createTime', 'desc').skip((pageNum - 1) * pageSize).limit(pageSize).get({
      getCount: true
    });
    return res;
  },
  // 获取所有订单
  async getAllList(pageNum = 1) {
    let pageSize = 5;
    let res = await dbJql.collection("ly-mall-order").where({
      status: cmd.neq(0)
    }).orderBy('createTime', 'desc').skip((pageNum - 1) * pageSize).limit(pageSize).get({
      getCount: true
    });
    return res;
  },
  //根据订单号获取订单信息
  async searchOrdersList(searchVal) {
    let res = await dbJql.collection("ly-mall-order").where(
      `${new RegExp(searchVal, 'i')}.test(order_no)`
    ).get();
    return res;
  },
  //订单更新为完成
  async updateOrder(orderNo) {
    //判断是否为管理员
    if (!this.userInfo.role.includes('manage')) {
      return {
        msg: '没有操作权限',
        code: -1
      }
    }
    let res = await db.collection("ly-mall-order").where({
      order_no: orderNo
    }).update({
      done: true
    })
    return res;
  },
  async demo() {
    let now = Date.now() - 3 * 60 * 60 * 1000;
    let res = await db.collection("ly-mall-order").where({
      status: cmd.eq(0),
      createTime: cmd.lte(now)
    }).remove();

    return res;
  },
  // 订单退款
  async updateRefundOrder(data) {
    //判断是否为管理员
    if (!this.userInfo.role.includes('manage')) {
      return {
        msg: '没有操作权限',
        code: -1
      }
    }
    let res = await db.collection("ly-mall-order").where({
      out_trade_no: data.outTradeNo
    }).update({
      refund_data: data,
      status: 3,
      done: true
    })
    return res;
  },
  // 未付款订单定时取消(3个小时前的订单)
  async _timing() {
    let now = Date.now() - 3 * 60 * 60 * 1000;
    let res = await db.collection("ly-mall-order").where({
      status: cmd.eq(0),
      createTime: cmd.lte(now)
    }).remove();

    return res;
  }
}

function getOrderId() {
  return Date.now() + "_" + String(Math.random()).substring(3, 9);
}